import React,{ PureComponent } from 'react';
import { Tree ,Input, } from 'antd';
import  debounced  from 'lodash.debounce' ;
import {CloseOutlined} from '@ant-design/icons';
import style from  './index.less';
import  { filterKey, signKey,addLayer,setLayerVisible} from './utils'

const { TreeNode } = Tree;

/**
 * 获取指定节点的父级key
 * @param {*} key 节点key
 * @param {*} tree 树的数据源对象
 */
const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};
const layerDicts = {};
class Trees extends PureComponent{

        state = {
          mapData:[], // tree 数据
          readonlyData:[],  // tree 只读
          expandedKeys: [],
          searchKey:'',
          autoExpandParent:true,
          checkedKeys: [],
          selectedKeys: [],
          unchecked:[], // 取消选择得Tree
        };

       componentDidMount(){
        fetch('/config/maplayer.json').then(response=>response.json()).then(data=>{
          // 构造图层树
          this.setState(preState => {
              return{
                mapData:data.layerList,
                readonlyData:data.layerList,
                expandedKeys:filterKey(data.layerList,'key'),
                checkedKeys:signKey(data.layerList,'show','children','key'),
              }
           },()=>{
              const unchecked = [];
              data.layerList.map(layerValue=>{
                layerValue.children.map(childValue=>{
                  // addLayer(childValue);
                  layerDicts[childValue.key] = childValue;
                  if(childValue.show)
                  {
                    unchecked.push(childValue.key);
                  }
                })
              });
              this.setState({unchecked})
           });
          // 添加图层到场景
          data.layerList.map(layerValue=>{
            layerValue.children.map(childValue=>{
              addLayer(childValue)});
          });
      });
       }

        onExpand = expandedKeys => {
          this.setState({
            expandedKeys,
            autoExpandParent : false,
          });
        };

      onCheck = (checkedKeys,e) => {
        const { expandedKeys,unchecked} = this.state;
        const oldCheckedKeys = this.state.checkedKeys.filter(item=>{ return expandedKeys.indexOf(item) == -1 });
        const checkedData0 =  checkedKeys.filter(item=>{ return expandedKeys.indexOf(item) == -1 })
        const checkedData = checkedData0.filter(item=>{ return oldCheckedKeys.indexOf(item) == -1 })

        const uncheckedData =  oldCheckedKeys.filter(item=>{ return checkedData0.indexOf(item) == -1 })
        checkedData.map(checkedValue => {
          setLayerVisible(layerDicts[checkedValue],true)
        });
        uncheckedData.map(uncheckedValue =>{
          setLayerVisible(layerDicts[uncheckedValue],false)
        });
        this.setState({ checkedKeys,checkedData,unchecked:oldCheckedKeys});
      };


      // tree 子级过滤   data:Object[]; checked:string;
      fillter =(data,checked) =>{
           for(let i=0, {length} = data; i<length;i++){
              if(data[i].title.includes(checked)) return true
              if(data.children){this.fillter(data.children,checked) }else{ return false}
           }
      }

     /**
     * 树节点筛选高亮
     */
    onFilter=(node)=>{
      const {searchKey}=this.state;
      const text=node.props.text||node.props.title;
      if(searchKey){
          return text.indexOf(searchKey)>-1;
      }
          return false;
      
  };

     // tree 过滤   data:Object[]; checked:string;500ms请求一次
      pitchTree = debounced((value) => {
        const {mapData}=this.state;
        const _expandedKeys=[];
        if(value){
          mapData.map(layer=>getNodeChildren(layer));
            this.setState({searchKey:value,expandedKeys:_expandedKeys});
        }else{
            this.setState({searchKey:"",expandedKeys:[],autoExpandParent: true});
        }
        function getNodeChildren(catalog){
           if(catalog.title.indexOf(value)>-1){
                let parentKey=getParentKey(catalog.key,mapData);
                if(!_expandedKeys.includes(parentKey)){
                    _expandedKeys.push(parentKey);
                }
                // 获得所有父级的key
                for(let i=0;i<99;i++){
                    parentKey=getParentKey(parentKey,mapData);
                    if(!parentKey)
                        break;
                    if(!_expandedKeys.includes(parentKey)){
                        _expandedKeys.push(parentKey);
                    }
                }
            }
            if(catalog.children&&catalog.children.length>0){
                catalog.children.map(item=>getNodeChildren(item));
            }
        }
             },500);


    // 渲染子级
    renderTreeNodes = data =>
    data&&data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} />;
    });

    render(){
        const  { mapData }= this.state;

        return(
          <>
          {this.props.show&&(
            <div className={style.treesRoot}>
                 <div>
                 <div className="unfold"><CloseOutlined onClick={()=>this.props.hideShow()} title="关闭"/> </div>
                 <Input
                    size="small"
                    placeholder="请输入查询图层"
                    onChange={e => {this.pitchTree(e.target.value)}}
                  />
                 </div>
                         <Tree
                         checkable
                         onExpand={this.onExpand}
                         expandedKeys={this.state.expandedKeys}
                         defaultExpandAll
                         onCheck={this.onCheck}
                         checkedKeys={this.state.checkedKeys}
                         onSelect={this.onSelect}
                         filterTreeNode={this.onFilter}
                         selectedKeys={this.state.selectedKeys}
                       >
                    {this.renderTreeNodes(mapData)}
                </Tree>
            </div>
          )}
          </>

        )
    }
}

export default Trees
